<template>
  <Tree
  @on-check-change="handleCheckSelect"
  show-checkbox
  multiple
  :data="data2"></Tree>
</template>
<script>
export default {
  name: 'PickTree',
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    checkedMenus: {
      type: Array,
      default: () => {
        return []
      }
    },
    labelKey: {
      type: String,
      default: () => {
        return 'title'
      }
    },
    valueKey: {
      type: String,
      default: () => {
        return 'code'
      }
    }
  },
  data () {
    return {
      data2: [],
      selectedNode: {
        key: '',
        value: ''
      },
      dataMap: []
    }
  },
  watch: {
    data: {
      handler: function (newVal, oldVal) {
        this.data2 = this.renderDataFromPropData(newVal)
        console.log(this.data2)
      },
      immediate: true,
      deep: true
    },
    checkedMenus: {
      handler: function (val) {
        if (val.length > 0) {
          this.renderDataFromPropData(this.data2)
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted () {
  },
  methods: {
    renderDataFromPropData (val) {
      let formatData = []
      if (val instanceof Array && val.length > 0) {
        val.map(item => {
          const cell = {
            title: item[this.labelKey], // 显示
            value: item[this.valueKey], // 值
            expand: true
          }
          if (typeof item.checked !== 'undefined') cell.checked = item.checked
          if (typeof item.selected !== 'undefined') cell.selected = item.selected
          if (item.children) {
            cell.children = this.renderDataFromPropData(item.children)
          }
          formatData.push(cell)
        })
        return formatData
      }
    },
    handleCheckSelect (node) {
      this.$emit('on-check-change', node)
    }
  }
}
</script>
